package com.humh.stock.common;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Map;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * <p>HttpClient工具</p>
 * Create by hgx61 at 2024/10/18
 */

public class HttpClientUtils {


  private static final ObjectMapper objectMapper = new ObjectMapper();

  /**
   * 发送 GET 请求
   */
  public static JsonNode sendGet(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
    String paramStr = paramsToQueryString(params);
    HttpGet request = new HttpGet(url + paramStr);

    // 设置请求头
    setHeaders(request, headers);

    try (CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = httpClient.execute(request)) {
      return handleResponse(response);
    }
  }

  /**
   * 发送 POST 请求
   */
  public static JsonNode sendPost(String url, Map<String, String> headers, Object body) throws Exception {
    HttpPost postRequest = new HttpPost(url);

    // 设置请求头
    setHeaders(postRequest, headers);

    // 设置请求体
    StringEntity entity = new StringEntity(objectMapper.writeValueAsString(body), "UTF-8");
    postRequest.setEntity(entity);
    postRequest.setHeader("Content-type", "application/json");

    try (CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = httpClient.execute(postRequest)) {
      return handleResponse(response);
    }
  }

  /**
   * 发送 PUT 请求
   */
  public static JsonNode sendPut(String url, Map<String, String> headers, Object body) throws Exception {
    HttpPut putRequest = new HttpPut(url);

    // 设置请求头
    setHeaders(putRequest, headers);

    // 设置请求体
    StringEntity entity = new StringEntity(objectMapper.writeValueAsString(body), "UTF-8");
    putRequest.setEntity(entity);
    putRequest.setHeader("Content-type", "application/json");

    try (CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = httpClient.execute(putRequest)) {
      return handleResponse(response);
    }
  }

  /**
   * 发送 DELETE 请求
   */
  public static JsonNode sendDelete(String url, Map<String, String> headers, Map<String, String> params)
      throws Exception {
    String paramStr = paramsToQueryString(params);
    HttpDelete deleteRequest = new HttpDelete(url + paramStr);

    // 设置请求头
    setHeaders(deleteRequest, headers);

    try (CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = httpClient.execute(deleteRequest)) {
      return handleResponse(response);
    }
  }

  /**
   * 处理 HTTP 响应，返回 JSON 对象
   */
  private static JsonNode handleResponse(CloseableHttpResponse response) throws Exception {
    String jsonResponse = EntityUtils.toString(response.getEntity(), "UTF-8");
    return objectMapper.readTree(jsonResponse);  // 解析为 Jackson 的 JsonNode 对象
  }

  /**
   * 将 Map 转换为查询字符串
   */
  private static String paramsToQueryString(Map<String, String> params) {
    if (params == null || params.isEmpty()) {
      return "";
    }
    StringBuilder queryString = new StringBuilder("?");
    for (Map.Entry<String, String> entry : params.entrySet()) {
      queryString.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
    }
    queryString.setLength(queryString.length() - 1);  // 移除最后的 "&"
    return queryString.toString();
  }

  /**
   * 设置请求头
   */
  private static void setHeaders(HttpRequestBase request, Map<String, String> headers) {
    if (headers != null) {
      for (Map.Entry<String, String> entry : headers.entrySet()) {
        request.setHeader(entry.getKey(), entry.getValue());
      }
    }
  }
}



